/*
NAME: 
DESCRIPTION: ;
PARAMETER:
    [
		{
			name: 'step_filter',
			title: 'step过滤',
			type: 'LineEdit'
		},
		{
			name : 'auto_save',
			title : '自动保存',
			type : 'RadioBox',
            property : {
				item_list:[
					{name:'yes',text:'Yes'},
					{name:'no',text:'No'},
				],
				tool_tip:'是否自动保存料号开关'
			}
        }
	]
	
 VERSION_HISTORY:
	V1.00 2020-04-20 Scott Sun
	    1.新版本
		
 HELP:
 	<html><body bgcolor="#DDECFE">
		<font size="3" color="#003DB2"><p>功能简介</p></font>
		<p> pad对齐 </p>
		<br>
		<font size="3" color="#003DB2"><p>参数配置</p></font>
		<p> </p>
		<br>
		<font size="3" color="#003DB2"><p>注意事项</p></font>
		<p> 无 </p>
		<br>
	</body></html>	
*/
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
console.log("================================>pad 对齐");
// 引入模块 包
var $ = require('topcam.scriptfunc').argv();
var fs = require('fs');
var _ = require('lodash');
var mode = $.ikm ? "topcam" : "aimdfm";
var IKM = $.ikm; 
if (IKM==undefined ) { IKM = require('topcam.ikm6')($) }
var GEN = $.gen;
var GUI = $.gui || {};
var Job = $.job || $.job_name;
var JobId = $.job_id;
var db = $.db || IKM.db
var PAR = {}
if ($.par) {
	PAR = $.par
} else if ($.hasOwnProperty('script_parameter')){
	PAR = JSON.parse($.script_parameter);
}
if (mode === "aimdfm") {
	var database = require("topsin.database");
	database.addConnection($.conf.database_conf, "DFM");
	var QDfm = database.query("DFM");
	$.QDfm = QDfm;
	if ($.conf.product_type == "aimdfm") {
		QDfm.updateRow({
			table: "pdm_aimdfm_task",
			data: {
				current_process_title: $.process_title
			},
			where: { id: $.task_id }
		});
	}
}
var Status = 'ok';
var resultData = [];

try {
	var par = PAR;
	var default_par = {
		step_filter:'net.+',
		step2:"net",
		max_via_size: "0.9mm",
		min_via_num: "100",
		equidistant_tolerance: "0.005mm", 
        auto_save: "No",
        units: "mm",
	}
	for(var key in default_par){  // 设置默认属性
		if (!par.hasOwnProperty(key) || par[key] == ""){
			par[key] = default_par[key]
		}
	}

	var max_via_size = parseFloat(par.max_via_size);
	var equidistant_tolerance = parseFloat(par.equidistant_tolerance);
	
	if(_.isEmpty(Job)){throw "参数Job不存在"}
	var job = Job.toLowerCase()
	if(!GEN.isJobExists({job:job})){throw "料号"+job+"不存在"}
	if(!GEN.isJobOpen({job:job})){ GEN.openJob({job:job}) }
    if(mode == "aimdfm"){
        if(GEN.checkInout({job:job,mode:"test"}) != 0){ throw "the job check" }
        GEN.checkInout({job:job,mode:"out"});
    }

	var matrix = GEN.getMatrix({job:job})

	var work_layers = Object.keys(matrix).filter(function(v){
		var info = matrix[v];
		return info.layer_type == "signal" && info.context=="board"&& /top|bot/.test(info.side)
	})

	var steplist = GEN.getStepList({job:job})
	steplist = steplist.filter(function(v){
		var tmpreg = new RegExp(par.step_filter,"ig")
		return tmpreg.test(v)
	})
	if (steplist.length == 0 && par.step2) {
		steplist = GEN.getStepList({job:job}).filter(function (v) {
			var tmpreg = new RegExp(par.step2, "ig");
			return tmpreg.test(v);
		})
	}
	steplist.forEach(function(step){
        GEN.openStep({job:job,name:step});

		// GEN.addText({fontname:"fs.shx",text:str,,x:0,y:0,x_size:100, y_size:100})

        //料号初始化
		GEN.clearLayers();  //清除层显示
		GEN.affectedLayer({ mode: 'all', affected: 'no' });  //设置影响层全部不影响
		//操作模式初始化
		GEN.COM("sel_options,clear_mode=clear_after,display_mode=all_layers,area_inout=inside,area_select=select,select_mode=standard,area_touching_mode=exclude");
		GEN.units({ type: par.units });  //单位初始化
        GEN.zoomHome();  //窗口显示回到原始位置
		
		var tmpchk = "pad_snap"
		if(GEN.isChklistExists({job:job,step:step,chklist:tmpchk})){
			GEN.COM("chklist_delete,chklist="+tmpchk)
		}
		GEN.units({ type: "mm" });  //单位初始化
		GEN.COM("chklist_create,chklist="+tmpchk)
		GEN.COM("chklist_show,chklist="+tmpchk)
		GEN.COM("chklist_single,action=valor_dfm_pad_snap,show=yes")
		GEN.COM("chklist_pclear")
		GEN.COM("chklist_cupd,chklist=valor_dfm_pad_snap,nact=1,params=((pp_layer=drl)(pp_ref_layer=.affected)(pp_max_snapping=50)),mode=regular") // (pp_ref_layer=lyr1)
		GEN.COM("chklist_pcopy,chklist=valor_dfm_pad_snap,nact=1")
		GEN.COM("chklist_close,chklist=valor_dfm_pad_snap,mode=hide")
		GEN.COM("chklist_ppaste,chklist="+tmpchk+",row=0")
	
		
		// GEN.COM("chklist_single,action=valor_dfm_pad_snap,show=yes")

        // // 不存在的属性就是默认
        // // 层名是事前设置好的，此处测试需要我改层名
        // GEN.runSingleDfm({
        // 	chklist: 'valor_dfm_pad_snap',
        // 	params: {
        // 		pp_layer: "gtl",
        // 		// pp_snap_to: 'Ref Layer',
        // 		// pp_ref_layer: gtl_name,
        // 		// pp_max_snapping: 50,
        // 		// pp_ignore_attr: '.bga',
        // 		// pp_include_smds: 'No'
        // 	}
        // });

        // GEN.runSingleDfm({
        // 	chklist: 'valor_dfm_pad_snap',
        // 	params: {
        // 		pp_layer: 'gbl',
        // 		// pp_snap_to: 'Ref Layer',
        // 		// pp_ref_layer: drl_name,
        // 		// pp_max_snapping: 50,
        // 		// pp_ignore_attr: '.bga',
        // 		// pp_include_smds: 'No'
        // 	}
        // });

		// work_layers.forEach(function(layer, i){
		// 	GEN.COM("chklist_single,action=valor_dfm_pad_snap,show=yes")
		// 	GEN.COM("chklist_pclear")
		// 	GEN.COM("chklist_cupd,chklist=valor_dfm_pad_snap,nact=1,params=((pp_layer="+layer+")(pp_ref_layer=drl)(pp_max_snapping=50)),mode=regular") // (pp_ref_layer=lyr1)
		// 	GEN.COM("chklist_pcopy,chklist=valor_dfm_pad_snap,nact=1")
		// 	GEN.COM("chklist_close,chklist=valor_dfm_pad_snap,mode=hide")
		// 	GEN.COM("chklist_ppaste,chklist="+tmpchk+",row=" + (i+1))
		// })

		GEN.workLayer({name:'drl',display_number:2,clear_before:'yes'})
		GEN.affectedLayer({affected:'no',mode:'all'})
		GEN.affectedLayer({affected:'yes',layer:work_layers})
		GEN.chklistRun({chklist:tmpchk})
		
		var nacts = GEN.getChklistActCount({job:job,step:step,chklist:tmpchk});
		
		var means = [];
		
		
		for (var index = 1; index <= nacts; index++) {
			means = means.concat(GEN.getCheckMeas({job:job,step:step,chklist:tmpchk,nact:index,severity:"",units:"mm"})		)
		}
		
		
		var snap_drls = means.filter(function(v){return v != "" && /^snapped/.test(v)})
		var unsnap_drls = means.filter(function(v){return v != "" && /^un_snapped/.test(v)})
		
        GEN.clearLayers();
		GEN.affectedLayer({ mode: 'all', affected: 'no' });
		var layers = Object.keys(GEN.getMatrix({job:job}))
		GEN.deleteLayer({job:job, step:step, layer:layers.filter(function(v){return /\+\+\+$/.test(v)})}) //删除复制的层 
		// ["snapped drl 0.383 mil r31.496 r70.866 SG 0.9448865 3.6811059 0.9448865 3.6807233 2 G"]
		if(snap_drls.length){
			IKM.msg("孔盘误差≤50um的孔已校正");
		}
		if(unsnap_drls.length){
			GEN.chklistShow({chklist:tmpchk})
			GEN.workLayer({name:'drl',display_number:2,clear_before:'yes'})

			unsnap_drls.forEach(function(v){
				var tmp = /un_snapped \S+ \S+ \S+ \S+ \S+ \S+ (\S+) (\S+) (\S+) (\S+)/.exec(v);
				GEN.COM("sel_single_feat,operation=select,x="+tmp[1]+",y="+tmp[2]+",cyclic=yes")
			})
			IKM.msg("孔盘误差＞50um的孔请按预审指示制作")
			GEN.PAUSE("pause")
		}
		work_layers.forEach(function(v, i){
			GEN.displayLayer({name:v, number:i + 2})
		})
		GEN.workLayer({name:'drl',display_number:1})
		GEN.units({ type: par.units });  //单位初始化
	})

	//保存 
	if(/yes/ig.test(par.auto_save.toLowerCase())){  //
		GEN.checkInout({job:job,mode:"out"})  // 结束保存料号 关闭料号
		GEN.saveJob({ job: job });
		GEN.checkInout({job:job,mode:"in"})
		GEN.closeJob({job:job})
	} else {
		GEN.checkInout({job:job,mode:"in"})
	}

    if (mode === "aimdfm") {
		$.QDfm.updateRow({
			table: "pdm_aimdfm_task",
			data: {
				progress: 33.33
			},
			where: { id: $.task_id }
		});
		if (GEN.hasError()) {
			Status = 'error';
			resultData.push({ type: "error", title: "GEN错误!", detail: [{ desc: _.join(GEN.STATUS, "\n") }] });
			return {
				status: Status,
				result_data: resultData
			};
		} else {
			resultData.push({ type: "info", title: "操作完成, 请注意检查!" });
			return {
				status: Status,
				result_data: resultData
			};
		}
	}else {
		return "Done"
	}   
} catch (e) {
	IKM.msg(_.join(GEN.STATUS, "\n"))
	IKM.msg(e)
    Status = 'error';
    resultData.push({type: "error", title: "脚本执行出错!", detail: [{desc: _.toString(e)}]});
	return (mode === "aimdfm") ? {status: Status, result_data: resultData} : "Error";
}